package proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;
import com.service.OrderService;
import com.service.impl.OrderServiceImpl;

import java.lang.reflect.Method;

/**
 * @author 徒有琴
 */
public class CGlibOrderProxy {
    private final OrderService orderService = new OrderServiceImpl();
    private OrderService proxy;

    public CGlibOrderProxy() {
        Enhancer enh = new Enhancer();
        enh.setSuperclass(orderService.getClass());
        enh.setCallback(new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("start...");
                //res被代理的对象方法的返回值
                //method调用的是被代理对象的哪个方法，args调用方法的参数
                Object res = method.invoke(orderService, args);//调用被代理的对象的方法
                System.out.println("end。。。");
                return res;
            }
        });
        proxy = (OrderService) enh.create();
    }

    public OrderService getProxy() {
        return proxy;
    }
}
